package com.feng.common.exception;

import com.feng.common.api.ResponseResult;
import com.feng.common.api.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Feng
 * @since 2022/4/18 10:10
 */

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 权限校验异常
     */
    @ExceptionHandler(value = AccessDeniedException.class)
    public ResponseResult handleException(AccessDeniedException e, HttpServletRequest req) {
        log.error("请求地址: '{}', 失败原因: '{}'", req.getRequestURI(), ResultCode.FORBIDDEN.getMsg());
        return new ResponseResult(ResultCode.FORBIDDEN);
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseResult handleException(HttpRequestMethodNotSupportedException e, HttpServletRequest req) {
        log.error("请求地址'{}',不支持'{}'请求", req.getRequestURI(), e.getMethod());
        return new ResponseResult(ResultCode.HTTP_BAD_METHOD);
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(value = BaseException.class)
    public ResponseResult handlerException(BaseException e, HttpServletRequest req) {
        log.error("请求地址: '{}', 失败原因: '{}'", req.getRequestURI(), e.getMessage());
        return new ResponseResult(e.getCode(), e.getMessage(), null);
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseResult handlerException(MethodArgumentNotValidException e, HttpServletRequest req) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("请求地址: '{}', 失败原因: '{}'", req.getRequestURI(), message);
        return new ResponseResult(ResultCode.PARAM_NOT_MATCH.getCode(), message, null);
    }

    /**
     * 其他异常
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseResult handlerException(Exception e, HttpServletRequest req) {
        e.printStackTrace();
        log.error("请求地址: '{}', 失败原因: '{}'", req.getRequestURI(), e.getMessage());
        return ResponseResult.error();
    }
}
